<?php 
/* This file contains everything about user management. 
 * login, logout, register, profile, update profile, change password etc...
 */
 
 //seconds required to timeout a user and make him/her offline
define('user_inactive_timeout',2,true);//60s


//user management action links (user authorization)	
$user_prefix = $index_page . "?user=";
	$user_signout = $user_prefix . "trysignout";
	$user_tryregister = $user_prefix . "tryregister";
	$user_trysignin = $user_prefix . "trysignin";
	$user_tryupdate = $user_prefix . "tryupdate";
	$user_trychangepassword = $user_prefix . "trychangepassword";
 
 
 	//select a single record from returns table
 	//returns $user
 	function selectSingleFromUsers($what,$whereKey,$whereVal,$otherConds=""){
		$result = select($what,table_users,$whereKey,$whereVal,$otherConds);
		return $result[0];
	}

	function updateUsers($userid,$updateItem,$updateValue){
		return updateSingleField(table_users,"id",$userid,$updateItem,$updateValue);
	}
	
	function updateNickname($user,$newnickname){
		$newnickname=mysql_escape_string($newnickname);
		return updateUsers($user['id'],'nickname',$newnickname);
	}

	//user related database functions
	//$userid -> $user
	function getUserById($userid){
		return selectSingleFromUsers("*","id",$userid);
	}
	
	//$username is a single name whereas $user is an array of all user data including the name
	//$username -> $user
	function getUserByName($username){
		return selectSingleFromUsers("*","loginname",$username);
	}
	
	//$user -> boolean (active/inactive)
	function getUserStatus(&$user){
		$lastactivity = $user['lastactivity'];
		//if last activity is more than timeout,
		if (time()-$lastactivity>user_inactive_timeout){
			return false;
		} else {
			return true;
		}
	}
	
	function changePassword($userid,$newpassword){
		return updateUsers($userid,"password",$newpassword);
	}
	
	//initializes the movehistory of user in users table
	//e.g. "1:0,0;2:0,0;3:0,0;4:0,0;5:0,0" is saved in table
	function initUserMovehistory(){
		global $difficulty;
		foreach($difficulty as $key=>$value){
			$result[]="$key:0,0";
		}	
		$result=implode(";",$result);
		return $result;
	}
	
	//registers new user in table
	function registerNewUser($loginname,$password,$nickname){
		if (!getUserByName($loginname)){
			$md5_password = md5($password);
			$time=time();
			$movehistory=initUserMovehistory();
			$loginname=$loginname;
			$nickname=$nickname;
			$chatlogid=createNewChatSession();
			$query = "INSERT INTO `".table_users."` " .
					"(`loginname`, `password`, `nickname`, `movehistory`, `chatlogid`, `lastactivity`) " .
					"VALUES('$loginname', '$md5_password', '$nickname', '$movehistory', '$chatlogid', '$time');";
			if (mysql_query($query)){
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	
	//save gameid of game last played by user in users table
	function setLastplayedgame(&$user,&$game){
		//update user session as well
		$user['lastplayedgameid']=$game['gameid'];
		return updateUsers($user['id'],"lastplayedgameid",$game['gameid']);
	}
	function setLastcreatedgame(&$user,&$game){
		//update user session as well
		$user['lastcreatedgameid']=$game['gameid'];
		return updateUsers($user['id'],"lastcreatedgameid",$game['gameid']);
	}
	
	//remove gameid of game created by user from users table
	function resetCreatedGame(&$user){
		$user['lastcreatedgameid']=null;
		return updateUsers($user['id'],"lastcreatedgameid",null);
	}
	
	//remove gameid of game last played by user in users table
	function resetLastPlayedGame(&$user){
		$user['lastplayedgameid']=null;
		return updateUsers($user['id'],"lastplayedgameid",null);
	}
	
	//update the time of user's last request
	function setUserLastActivity(&$user){
		$time=time();
		$user['lastactivity']=$time;
		return updateUsers($user['id'],"lastactivity",$time);
	}
	
//end of user related functions

/* Processing of user related requests begin here
 * $user = array(id,loginname,nickname,password,movehistory,score,
 *				 lastplayedgameid,lastcreatedgameid,lastactivity)
 */	
 //first of all, check if the user exists, else, terminate user session.
 //Load user info from session

if (isset($_SESSION['user']) && $_SESSION['user']){
	$user=$_SESSION['user'];
	if ($user){
		$user=getUserById($user['id']); //check if user from session exists in database
	} else {
		$user=null;
	}
}
 
if (isset($_GET['user'])){
	$useraction = $_GET['user'];
	//dispatch request for user account signin, signout, register, update etc
	switch ($useraction){
		case 'trysignin': //non ajax-request
			if (isset($_POST['login_user']) && $_POST['login_user']){
				$login_user=$_POST['login_user'];
				$login_pass='';
				if (isset($_POST['login_pass']) && $_POST['login_pass']){
					$login_pass=$_POST['login_pass'];
					$fetched_user = getUserByName($login_user);
					if ($fetched_user['password']==md5($login_pass)){
						//if password matches, sign in success
						$user=$fetched_user;
						$page=page_signinsuccess;
						$submit_fail_msg='';
					} else { 
						//password wrong
						$page=page_signin;
						$submit_fail_msg='We are sorry. Your password is not working. Perhaps capslock is on? Please check your username as well. Thank you!';
					}
				} else {
					//password empty
					$page=page_signin;
					$submit_fail_msg='Could you supply your password for us to validate?';
				}
			} else {
				//login name empty
				$page=page_signin;
				$submit_fail_msg='It is hard for us to log you in without your username.';
			}
			break;
	
		case 'tryregister': //non-ajax request
			//check for registration
			if (isset($_POST['reg_loginuser']) && $_POST['reg_loginuser']){
				$loginuser=$_POST['reg_loginuser'];
				
				if (isset($_POST['reg_password']) && $_POST['reg_password']){
					$confirm=$_POST['reg_confirm'];
					$password=$_POST['reg_password'];
					if ($confirm==$password){
						if (isset($_POST['reg_nickname']) && $_POST['reg_nickname']){
							$nickname=$_POST['reg_nickname'];
							if (!getUserByName($loginuser)){
								if (registerNewUser($loginuser,$password,$nickname)){
									$user=getUserByName($loginuser);
									$page=page_signupsuccess;	
									$submit_fail_msg="";
								} else {
									//registration failed
									$page=page_signup;	
									$submit_fail_msg="Registration failed. A bug is biting our database registration.";
								}
							} else {
								//user exists
								$page=page_signup;	
								$submit_fail_msg="Unfortunately, the login name you have chosen is already taken. Could you give us one more chance?";
							}
						} else {
							//nickname empty
							$page=page_signup;	
							$submit_fail_msg='How would you like your friends to call you? Please tell us your nickname or else, our admins might supply you one. :P';
						}
					} else {
						//password confirmation failed
						$page=page_signup;	
						$submit_fail_msg='Your two passwords do not match.';
					}
				} else {
					//password empty
					$page=page_signup;	
					$submit_fail_msg='For your own safety, please supply the password';
				}
			} else {
				//login name empty
				$page=page_signup;
				$submit_fail_msg='Could you please tell us your log in name at least? xD';
			}
			break;
		case 'tryupdate': //non-ajax request
			if (isset($_POST['upd_loginname']) && $_POST['upd_loginname']){
				$upd_loginname=$_POST['upd_loginname'];
				if (isset($_POST['upd_nickname']) && $_POST['upd_nickname']){
					$upd_nickname=$_POST['upd_nickname'];
					if (updateNickname($user,$upd_nickname)){
						$user=getUserById($user['id']);
						$submit_fail_msg='';
						$page=page_editprofile;
						$submit_msg='Your new cool nickname has been updated.';
					} else {
						$page=page_editprofile;
						$submit_fail_msg='For unknown reasons, we could not update your new marvelous nickname. May be invalid characters? o.O';
					}
				} else {
					//empty nickname
					$page=page_editprofile;
					$submit_fail_msg='Nickname cannot be empty :(';
				}
			} else {
				$page=page_editprofile;
				$submit_fail_msg='For some unknown reasons, we could not identify your login name. Please allow us to fix this problem.';
			}
			break;
		case 'trychangepassword': //non-ajax request
			if (isset($_POST['change_password']) && $_POST['change_password']){
					$confirm=$_POST['confirm_password'];
					$password=$_POST['change_password'];
					if ($confirm==$password){
						if (changePassword($user['id'],md5($password))){
							$user=getUserById($user['id']); //get back the preloaded user
							$page=page_editprofile;	
							$submit_fail_msg='';
							$submit_msg='It is of our utmost delight to have successfully changed new password for you ^^';
						} else {
							//update failed
							$page=page_changepassword;	
							$submit_fail_msg='For some strange reason, update failed. We are eager to fix it as soon as possible.';
						}
					} else {
						//password confirmation failed
						$page=page_changepassword;	
						$submit_fail_msg='Your two passwords do not match.';
					}
				} else {
					//password empty
					$page=page_changepassword;	
					$submit_fail_msg='For your own safety, please supply the password';
				}
			break;
		case 'trysignout': //non-ajax request
			$user=null;
			$page=page_signin;
			break;
	}
}
//redirect to signin page for unauthorized access.
if (!(isset($user) && $user!=null)){
	switch ($page){
		//add pages here to allow access without logging in.
		case page_home:
		case page_signin:
		case page_signup:
		case page_howto:
			break;
		//all other pages are access restricted
		default:
			$page=page_signin; //redirect to signin page
			break;
	}
} else {
	//finally, update the user's last activity time
	$result=setUserLastActivity($user);
}

?>